package com.mediacloud.app.newsmodule.activity;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.chinamcloud.collect.AcquisitionManager;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.GroupPhotoDataReciver.PhotoItem;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.view.BaseSpiderViewX;
import com.mediacloud.app.newsmodule.view.HackyViewPager;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.user.model.UserInfo;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class ImageDetailActivity extends StyleSetActivity implements DataInvokeCallBack<ArticleItemReciver> {

    private ViewPager mViewPager;
    private ArrayList<String> mPhotoUrls = new ArrayList<String>();
    protected List<PhotoItem> photos;
    protected boolean isDisposed;
    protected FrameLayout photoContent;
    protected TextView imageTitle, imageDes, positionTv;
    protected NewsDetailInvoker sewsDetailInvoker;


    @Override
    public boolean showTitleBar() {
        return false;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        catalogItem = getIntent().getParcelableExtra("catalog");
        articleItem = getIntent().getParcelableExtra("data");

        sewsDetailInvoker = new NewsDetailInvoker(this);
        initView();

        loadImageNewsDetail();
        decideTitileBarStyle();
        setTitle("");
        showStateView(TYPE_LOADING, false);
        onPageStart();
        showPageTransition();
    }


    @Override
    protected boolean openTitleBarSetting() {
        return true;
    }


    @Override
    public int getStatusBarColor() {
        return Color.WHITE;
    }

    ReadStatusInvoker readStatusInvoker;

    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    protected void initView() {
        positionTv = Utility.findViewById(mRootView, R.id.positionTv);
        imageTitle = findViewById(R.id.imageTitle);
        mTitileBar = findViewById(R.id.rlTitleBar);
        imageDes = findViewById(R.id.imageDes);
        photoContent = findViewById(R.id.photoContent);
        mViewPager = new HackyViewPager(this);
        photoContent.addView(mViewPager);
        findViewById(R.id.mTop_back).setOnClickListener(v -> finish());
        findViewById(R.id.mTitlebar_More).setOnClickListener(v -> shareWrap.show(mRootView));
    }

    @Override
    public void showStateView(String type, boolean forceDefault) {
        super.showStateView(type, forceDefault);

    }


    protected void decideTitileBarStyle() {
        if (isShowComment(articleItem)) {
            showCommentRelativeView(true);
        } else {
            showCommentRelativeView(false);
        }
    }


    public void loadImageNewsDetail() {
        imageTitle.setText(articleItem.getTitle());
        String navigate_id = catalogItem.getCatid();
        sewsDetailInvoker.getArticleById("" + articleItem.getId(),  navigate_id);
    }


    protected void setImages(ArticleItem item) {
        closeStateView();
        try {

            photos = new ArrayList<>();
            JSONArray jsonArray = new JSONArray(item.getImage());

            if (jsonArray.length() == 0) {
                mPhotoUrls.add("");
                PhotoItem photoItem = new PhotoItem();
                photoItem.setImage("");
                photoItem.setThumb("");
                photoItem.setNote("");
                photos.add(photoItem);
            }
            for (int i = 0; i < jsonArray.length(); i++) {
                PhotoItem photoItem = new PhotoItem();
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                String url = jsonObject.optString("src", "");
                String note = jsonObject.optString("info", item.getTitle());
                photoItem.setImage(url);
                photoItem.setThumb(url);
                photoItem.setNote(note);
                photos.add(photoItem);

                mPhotoUrls.add(url);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (mPhotoUrls.size() == 0) {
                mPhotoUrls.add("");
            }
        }
        mViewPager.setAdapter(new SamplePagerAdapter(mPhotoUrls));
    }


    private class SamplePagerAdapter extends PagerAdapter {
        private ArrayList<String> urls;
        private int urlsSize;

        public SamplePagerAdapter(ArrayList<String> urls) {
            this.urls = urls;
            urlsSize = urls.size();
        }

        @Override
        public int getCount() {
            return urlsSize;
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            if (position >= urlsSize) {
                return null;
            }
            AppCompatImageView pictureViewX = new AppCompatImageView(container.getContext());
            pictureViewX.setScaleType(ImageView.ScaleType.CENTER_CROP);
            pictureViewX.setId(View.generateViewId());
//            pictureViewX.mAttacher.setOnViewTapListener(new OnViewTapListener() {
//                @Override
//                public void onViewTap(View view, float x, float y) {
//                }
//            });
            pictureViewX.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        //    pictureViewX.setImageURL(urls.get(position));
            FunKt.load(pictureViewX,urls.get(position),0, AppFactoryGlobalConfig.defaultImageLoadDrawable,null);
            container.addView(pictureViewX, 0);
            return pictureViewX;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void setPrimaryItem(View container, int position, Object object) {
            if (photos.size() == 0)
                return;
            positionTv.setText((position + 1) + "/" + urlsSize);
            String note = photos.get(position).getNote();
            if (TextUtils.isEmpty(note) && articleItem != null)
                note = articleItem.getTitle();
            imageDes.setText(note);

        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    @Override
    protected void onDestroy() {
        isDisposed = true;
        if (sewsDetailInvoker != null) {
            sewsDetailInvoker.destory();
        }
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;
        if (photos != null)
            photos.clear();
        sewsDetailInvoker = null;
        super.onDestroy();
        catalogItem = null;
        articleItem = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
    }


    @Override
    public int getLayoutResID() {
        return R.layout.activity_image_detail;
    }


    protected void intoLogin(Context context) {
        //    ToastUtil.show(context, R.string.please_login);
        LoginUtils.request_source="图片详情";
        LoginUtils.invokeLogin(context);
    }

    @Override
    public void success(ArticleItemReciver data) {
        if (data.state && data.articleItem != null) {
            if (articleItem.getFromComponent() != 1) {
                articleItem = data.articleItem;
            }

            if (articleItem.getSpider() != null) {
                BaseSpiderViewX spiderView = findViewById(R.id.spiderView);
                spiderView.setDate(articleItem);
            }
            refreshBottomStyle(data.articleItem, 1);
            UserRecommend.addItemKeyWord(articleItem, this);
            if (!TextUtils.isEmpty(articleItem.getTitle()))
                imageTitle.setText(articleItem.getTitle());
            else
                imageTitle.setText(articleItem.getSummary());

            readStatus();
            decideTitileBarStyle();
            AddMedalStatistics.addMedalStatistics(this); //勋章统计
            startAddIntegralCounter();
            setImages(data.articleItem);
        } else {
            fault(null);
        }
    }

    private void startAddIntegralCounter(){
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
                Addintegral.addintegral(ImageDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });
    }

    @Override
    public void fault(Object data) {
        setImages(new ArticleItem());
        if (null == data) {
            showStateView(TYPE_NO_CONTENT, false);
        } else {
            showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }
}